package com.atguigu.tingshu.order.handler;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;
    //监听方法
    @PostConstruct
    public void listener() {
        //创建新线程一直监听延迟队列
        new Thread(()->{
            while(true) {
                try {
                    //从延迟队列获取消息
                    RBlockingQueue<String> blockingQueue =
                            redissonClient
                                    .getBlockingQueue(MqConst.EXCHANGE_CANCEL_ORDER);

                    //如果可以获取到，根据消息取消订单
                    String orderId = blockingQueue.take();

                    if(StringUtils.hasText(orderId)) {
                        //调用方法，根据orderId取消订单
                        orderInfoService.cancelOrder(Long.parseLong(orderId));
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
